package com.bocai.kelala.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bocai.kelala.R;
import com.bocai.kelala.ui.travel.main.presenter.MainPresenter;
import com.bocai.kelala.util.ToastUitl;


/**
 * Created by yuanfei on 2017/6/14.
 */

public class LoginDialog {
    private Context context;
    private Dialog dialog;
    private LinearLayout lLayout_bg, ll_phone;
    private TextView txt_title, tvPhone, tvCode;
    private ChangeTextSpaceView txtCode;
    private TextView txt_msg;
    private ProgressButton btn_confirm;
    private ImageView imgAgain;
    private EditText ed_first, ed_second;
    private Display display;
    private boolean showTitle = false;
    private boolean showMsg = false;
    private boolean showBtnConfirm = false;
    private boolean showEdFirst = false;
    private boolean showEdSecond = false;
    private boolean showLl1 = false;
    private boolean showLl2 = false;
    private boolean showLlImageCode = false;
    private boolean showLlSms = false;
    private boolean showLlPhone = false;
    private String phone;
    private LinearLayout llImageCode, llGetCode, llSms, ll1, ll2,llDetele,llFirst;
    private EditText ed1, ed2, ed3, ed4;
    private int index = 0;
    private ImageView line1, line2;
    private StringBuilder stringBuilder = new StringBuilder();
    private String letterString;
    MainPresenter presenter;
    private String smsCode;
    private boolean isRegister = false;
    private String code;



    public LoginDialog(Context context) {
        this.context = context;
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        display = windowManager.getDefaultDisplay();
    }

    public LoginDialog builder() {
        // 获取Dialog布局
        View view = LayoutInflater.from(context).inflate(
                R.layout.view_login_dialog, null);

        // 获取自定义Dialog布局中的控件
        lLayout_bg = (LinearLayout) view.findViewById(R.id.lLayout_bg);
        txt_title = (TextView) view.findViewById(R.id.txt_title);
        txt_title.setVisibility(View.GONE);
        txt_msg = (TextView) view.findViewById(R.id.txt_msg);
        txt_msg.setVisibility(View.GONE);
        btn_confirm = (ProgressButton) view.findViewById(R.id.btn_confirm);
        btn_confirm.setVisibility(View.GONE);
        ed_first = (EditText) view.findViewById(R.id.ed_first);
        ed_first.setVisibility(View.GONE);
        ed_second = (EditText) view.findViewById(R.id.ed_second);
        ed_second.setVisibility(View.GONE);
        ll_phone = (LinearLayout) view.findViewById(R.id.ll_phone);
        ll_phone.setVisibility(View.GONE);

        llImageCode = (LinearLayout) view.findViewById(R.id.ll_image_code);//图形验证码模块
        txtCode = (ChangeTextSpaceView) view.findViewById(R.id.txt_code);//重新获取图形验证码
        txtCode.setSpacing(24);
        imgAgain = (ImageView) view.findViewById(R.id.img_again);//重新获取图形验证码
        tvPhone = (TextView) view.findViewById(R.id.tv_phone);//手机号
        llGetCode = (LinearLayout) view.findViewById(R.id.ll_get_code);//获取短信验证码
        tvCode = (TextView) view.findViewById(R.id.tv_code);//倒计时
        llSms = (LinearLayout) view.findViewById(R.id.ll_sms);//短信验证码模块
        llFirst = (LinearLayout) view.findViewById(R.id.ll_first);

        ll1 = (LinearLayout) view.findViewById(R.id.ll1);
        ll2 = (LinearLayout) view.findViewById(R.id.ll2);
        llDetele = (LinearLayout) view.findViewById(R.id.ll_detele);

        ed1 = (EditText) view.findViewById(R.id.ed1);
        ed2 = (EditText) view.findViewById(R.id.ed2);
        ed3 = (EditText) view.findViewById(R.id.ed3);
        ed4 = (EditText) view.findViewById(R.id.ed4);

        line1 = (ImageView) view.findViewById(R.id.line1);
        line2 = (ImageView) view.findViewById(R.id.line2);

        // 定义Dialog布局和参数
        dialog = new Dialog(context, R.style.AlertDialogStyle);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.DialogAnim);
        // 调整dialog背景大小
        lLayout_bg.setLayoutParams(new FrameLayout.LayoutParams((int) (display
                .getWidth() * 0.85), LinearLayout.LayoutParams.MATCH_PARENT));
        llDetele.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                setRegister();
            }
        });
        setEditClick();
        return this;
    }


    public void setEditEmpty() {
        ed1.setText("");
        ed2.setText("");
        ed3.setText("");
        ed4.setText("");
        setFocuse();
        ed1.setFocusable(true);
        ed1.setFocusableInTouchMode(true);
        ed1.requestFocus();
    }

    public void setFocuse(){
        ed1.setFocusable(false);
        ed1.setFocusableInTouchMode(false);
        ed2.setFocusable(false);
        ed2.setFocusableInTouchMode(false);
        ed3.setFocusable(false);
        ed3.setFocusableInTouchMode(false);
        ed4.setFocusable(false);
        ed4.setFocusableInTouchMode(false);

    }

    public void setPresenter(MainPresenter presenter){
        this.presenter = presenter;
    }

    /**
     * editText 输入监听
     */
    public void setEditClick() {
        ed1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 1) {
                    setFocuse();
                    ed2.setFocusable(true);
                    ed2.setFocusableInTouchMode(true);
                    ed2.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ed2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.e("beforeTextChanged", s.toString() + "    " + start + "      " + count + "       " + after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.e("onTextChanged", s.toString() + "    " + start + "      " + before + "       " + count);
                if (count == 1) {
                    setFocuse();
                    ed3.setFocusable(true);
                    ed3.setFocusableInTouchMode(true);
                    ed3.requestFocus();
                } else if (count == 0) {
                    setFocuse();
                    ed1.setFocusable(true);
                    ed1.setFocusableInTouchMode(true);
                    ed1.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ed3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.e("onTextChanged1", s.toString() + "    " + start + "      " + before + "       " + count);
                if (count == 1) {
                    setFocuse();
                    ed4.setFocusable(true);
                    ed4.setFocusableInTouchMode(true);
                    ed4.requestFocus();
                } else if (count == 0) {
                    setFocuse();
                    ed2.setFocusable(true);
                    ed2.setFocusableInTouchMode(true);
                    ed2.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ed4.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 1) {
                    stringBuilder = new StringBuilder();
                    stringBuilder.append(ed1.getText().toString().trim());
                    stringBuilder.append(ed2.getText().toString().trim());
                    stringBuilder.append(ed3.getText().toString().trim());
                    stringBuilder.append(s.toString().trim());
                    if (index == 1) {//判断图形验证码
                        if (stringBuilder.toString().trim().equalsIgnoreCase(letterString)) {
                            presenter.sendCode(phone,"0");
                        }else {
                            Toast.makeText(context, "图形验证码错误", Toast.LENGTH_SHORT).show();
                        }
                    } else if (index == 2) {//短信验证码
                        smsCode = stringBuilder.toString().trim();
                        if (code.equals(smsCode)) {
                            setConfirmPw();
                        }else {
                            Toast.makeText(context, "短信验证码错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        ed2.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL&&event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(ed2.getText().toString().trim())) {
                        setFocuse();
                        ed1.setText("");
                        ed1.setFocusable(true);
                        ed1.setFocusableInTouchMode(true);
                        ed1.requestFocus();
                    }
                }
                return false;
            }
        });
        ed3.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL&&event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(ed3.getText().toString().trim())) {
                        setFocuse();
                        ed2.setText("");
                        ed2.setFocusable(true);
                        ed2.setFocusableInTouchMode(true);
                        ed2.requestFocus();
                    }
                }
                return false;
            }
        });
        ed4.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL&&event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(ed4.getText().toString().trim())) {
                        setFocuse();
                        ed3.setText("");
                        ed3.setFocusable(true);
                        ed3.setFocusableInTouchMode(true);
                        ed3.requestFocus();
                    }
                }
                return false;
            }
        });

        imgAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                StringBuilder letter = new StringBuilder();
                for (int i = 0;i<4;i++){
                    Log.e("letter",(int)(Math.random() * 26)+"");
                    letter.append(chars.charAt((int)(Math.random() * 26)));
                }
                letterString = letter.toString().trim();
                txtCode.setText(letterString);
            }
        });

    }

    public LoginDialog setTitle(String title) {
        showTitle = true;
        if ("".equals(title)) {
            txt_title.setText("标题");
        } else {
            txt_title.setText(title);
        }
        return this;
    }

    public LoginDialog setCancelable(boolean cancel) {
        dialog.setCancelable(cancel);
        return this;
    }

    public LoginDialog setConfirmButton(String text) {
        showBtnConfirm = true;
        if ("".equals(text)) {
            btn_confirm.setText("确定");
        } else {
            btn_confirm.setText(text);
        }
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (index == 0) {
                    btn_confirm.startRotate();
                    phone = ed_first.getText().toString().trim();
                    presenter.getPhoneType(phone);
                } else if (index == 3) {
                    if (TextUtils.isEmpty(ed_second.toString().trim())){
                        ToastUitl.showShort("请输入密码");
                    }else if (ed_second.toString().trim().length()<5){
                        ToastUitl.showShort("密码最少6位");
                    }else {
                        btn_confirm.startRotate();
                        isRegister = true;
                        presenter.register(phone, ed_second.getText().toString().trim(), smsCode, 1,0);
                    }

                }else if (index == 4){
                    if (TextUtils.isEmpty(ed_first.getText().toString().trim())){
                        ToastUitl.showShort("请输入手机号");
                    }else if (ed_first.getText().toString().trim().length()!=11){
                        ToastUitl.showShort("请输入正确的手机号");
                    }else if (TextUtils.isEmpty(ed_second.toString().trim())){
                        ToastUitl.showShort("请输入密码");
                    }else if (ed_second.toString().trim().length()<5){
                        ToastUitl.showShort("密码最少6位");
                    }else {
                        btn_confirm.startRotate();
                        presenter.login(ed_first.getText().toString().trim(),ed_second.getText().toString().trim(),"");
                    }
                }
            }
        });
        return this;
    }

    private void setLayout() {
        ll1.setVisibility(View.VISIBLE);
        ll2.setVisibility(View.GONE);
        if (!showTitle && !showMsg) {
            txt_title.setText("提示");
            txt_title.setVisibility(View.VISIBLE);
        }

        if (showTitle) {
            txt_title.setVisibility(View.VISIBLE);
        }

        if (showMsg) {
            txt_msg.setVisibility(View.VISIBLE);
        } else {
            txt_msg.setVisibility(View.GONE);
        }
        if (showEdFirst) {
            ed_first.setVisibility(View.VISIBLE);
            line1.setVisibility(View.VISIBLE);
            llFirst.setVisibility(View.VISIBLE);
        } else {
            ed_first.setVisibility(View.GONE);
            line1.setVisibility(View.GONE);
            llFirst.setVisibility(View.GONE);
        }
        if (showEdSecond) {
            ed_second.setVisibility(View.VISIBLE);
            line2.setVisibility(View.VISIBLE);
        } else {
            ed_second.setVisibility(View.GONE);
            line2.setVisibility(View.GONE);
        }
        if (showBtnConfirm) {
            btn_confirm.setVisibility(View.VISIBLE);
        } else {
            btn_confirm.setVisibility(View.GONE);
        }

        if (showLlPhone) {
            ll_phone.setVisibility(View.VISIBLE);
        } else {
            ll_phone.setVisibility(View.GONE);
        }
    }

    private void setLayout1() {
        ll1.setVisibility(View.GONE);
        ll2.setVisibility(View.VISIBLE);
        if (showTitle) {
            txt_title.setVisibility(View.VISIBLE);
        }
        if (showLlSms) {
            llSms.setVisibility(View.VISIBLE);
        } else {
            llSms.setVisibility(View.GONE);
        }

        if (showLlImageCode) {
            llImageCode.setVisibility(View.VISIBLE);
        } else {
            llImageCode.setVisibility(View.GONE);
        }

    }

    /**
     * 输入手机号
     */
    public void setEnterPhone() {
        index = 0;
        txt_title.setText("登录");
        ed_first.setText("");
        showEdFirst = true;
        showEdSecond = false;
        showBtnConfirm = true;
        showMsg = false;
        showLlPhone = true;
        btn_confirm.setText("下一步");
        btn_confirm.setEnabled(false);
        btn_confirm.removeDrawable();
        btn_confirm.setClickable(true);
//        if (!TextUtils.isEmpty(phone)) {
//            ed_first.setText(phone);
//            ed_first.setSelection(11);
//            btn_confirm.setEnabled(true);
//        }
        setLayout();
        ed_first.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)}); //最大输入长度
        ed_first.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (index == 0) {
                    if (ed_first.getText().toString().trim().length() == 11) {
                        btn_confirm.setEnabled(true);
                    } else {
                        btn_confirm.setEnabled(false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ed_first.setFocusable(true);
        ed_first.setFocusableInTouchMode(true);
        ed_first.requestFocus();
    }

    /**
     * 图形验证码
     */
    public void setPhotoCode() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder letter = new StringBuilder();
        for (int i = 0;i<4;i++){
            Log.e("letter",(int)(Math.random() * 26)+"");
            letter.append(chars.charAt((int)(Math.random() * 26)));
        }
        letterString = letter.toString().trim();
        txtCode.setText(letterString);
        index = 1;
        showLlImageCode = true;
        showLlSms = false;
        txt_title.setText("输入图片中的字母");
        ed1.setInputType(InputType.TYPE_CLASS_TEXT);
        ed2.setInputType(InputType.TYPE_CLASS_TEXT);
        ed3.setInputType(InputType.TYPE_CLASS_TEXT);
        ed4.setInputType(InputType.TYPE_CLASS_TEXT);
        setLayout1();
        setEditEmpty();
    }

    /**
     * 短信验证码
     */
    public void setSmsCode(String code) {
        this.code = code;
        index = 2;
        showLlImageCode = false;
        showLlSms = true;
        txt_title.setText("输入验证码");
        tvPhone.setText(phone);
        setLayout1();
        setEditEmpty();
        //发送验证码
        //发送验证码
        ed1.setInputType(InputType.TYPE_CLASS_NUMBER);
        ed2.setInputType(InputType.TYPE_CLASS_NUMBER);
        ed3.setInputType(InputType.TYPE_CLASS_NUMBER);
        ed4.setInputType(InputType.TYPE_CLASS_NUMBER);
        llGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.sendCode(phone,"0");
            }
        });
        tvPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setEnterPhone();
            }
        });
    }

    /**
     * 设置登录密码
     */
    public void setConfirmPw() {
        btn_confirm.removeDrawable();
        btn_confirm.setClickable(true);
        ed_second.setText("");
        index = 3;
        txt_title.setText("设置登录密码");
        txt_msg.setText("为保障您的账号安全，请您设置登录密码");
        showEdFirst = false;
        showEdSecond = true;
        showBtnConfirm = true;
        showMsg = true;
        showLlPhone = false;
        btn_confirm.setText("确认");
        setLayout();
        btn_confirm.setEnabled(false);
        ed_second.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (index == 3) {
                    if (ed_second.getText().toString().trim().length() > 5) {
                        btn_confirm.setEnabled(true);
                    } else {
                        btn_confirm.setEnabled(false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ed_second.setFocusable(true);
        ed_second.setFocusableInTouchMode(true);
        ed_second.requestFocus();
    }

    /**
     *密码登录
     */
    public void setLogin(){
        btn_confirm.removeDrawable();
        btn_confirm.setClickable(true);
        ed_first.setText(phone);

        index = 4;
        txt_title.setText("登录");
        txt_msg.setText("忘记密码");
        showEdFirst = true;
        showEdSecond = true;
        showBtnConfirm = true;
        showMsg = true;
        showLlPhone = false;
        btn_confirm.setText("确认");
        setLayout();
        btn_confirm.setEnabled(false);
        txt_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (index == 4){
                    setPhotoCode();
                }
            }
        });
        ed_first.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (index == 4) {
                    if (ed_second.getText().toString().trim().length() > 5 && ed_first.getText().length() == 11) {
                        btn_confirm.setEnabled(true);
                    } else {
                        btn_confirm.setEnabled(false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        ed_second.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (index == 4) {
                    if (ed_second.getText().toString().trim().length() > 5 && ed_first.getText().length() == 11) {
                        btn_confirm.setEnabled(true);
                    } else {
                        btn_confirm.setEnabled(false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ed_second.setText("");
        ed_second.setFocusable(true);
        ed_second.setFocusableInTouchMode(true);
        ed_second.requestFocus();
    }


    public void show() {
        phone = "";
        smsCode = "";
        isRegister = false;
        setLayout();
        btn_confirm.removeDrawable();
        btn_confirm.setClickable(true);
        dialog.show();
    }
    public void dismiss(){
        dialog.dismiss();
    }

    public void setBtn(){
        btn_confirm.removeDrawable();
        btn_confirm.setClickable(true);
    }
    public void setBtnCode(int index){
        if (index == 0) {
            llGetCode.setClickable(true);
            llGetCode.setEnabled(true);
            tvCode.setText("重新获取");
        } else {
            llGetCode.setClickable(false);
            llGetCode.setEnabled(false);
            tvCode.setText(index + "秒");
        }
    }

    /**
     * 无密码注册
     */
    public void setRegister(){
        if (index == 3&&!isRegister){
            presenter.register(phone,"",smsCode,1,1);
        }
        dialog.dismiss();
    }
}
